<?php
// $Id$

/**
 * Controller_Admin_Links controller
 */
class Controller_Admin_Links extends Controller_Abstract
{

    /**
     * 显示友情链接文章列表
     */
	function actionIndex()
    {
        $this->_view['links'] = Link::find()->order('type ASC, order_pos DESC')->getAll();
    }

    /**
     * 添加友情链接文章
     */
    function actionCreate()
    {
        $this->_viewname = 'edit';
        $form = Form_Admin_Link::createForm(url('links/create'));

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            try
            {
                $link = new Link($form->values());
                $link->save();

                return $this->_redirect(url('links/index'));
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                $form->invalidate($ex);
            }
        }

        $this->_view['form'] = $form;
    }

    /**
     * 编辑友情链接文章
     */
    function actionEdit()
    {
        $id = $this->_context->id;
        $link = Link::find('id = ?', $id)->query();
        if (!$link->id())
        {
            return $this->_redirect(url('links/index'));
        }
        $form = Form_Admin_Link::createForm(url('links/edit'));

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            try
            {
                $link->changeProps($form->values());
                $link->save();

                return $this->_redirect(url('links/index'));
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                $form->invalidate($ex);
            }
        }
        elseif (!$this->_context->isPOST())
        {
            $form->import($link);
        }

        $this->_view['form'] = $form;
    }

    function actionUpdate()
    {
        $delete = (array)$this->_context->delete;
        if (!empty($delete))
        {
            Link::meta()->destroyWhere('id IN (?)', $delete);
        }

        $new_order_pos = (array)$this->_context->order_pos;
        foreach ($new_order_pos as $id => $order_pos)
        {
            if (in_array($id, $delete)) continue;
            Link::meta()->updateWhere(array('order_pos' => $order_pos), 'id = ?', $id);
        }

        return $this->_redirect(url('links/index'));
    }
}


